package geekTime.chapter16Semaphore;

import java.util.List;
import java.util.Vector;
import java.util.concurrent.Semaphore;
import java.util.function.Function;

/**
 * 只允许n个线程访问的对象池，使用Semaphore实现限流器
 * Created by LinGer on 2019/6/27
 */
public class ObjPool {

    private final List<String> pool;

    /**
     * 利用信号量实现限流器
     */
    private final Semaphore sem;

    public ObjPool(Integer size, String t){
        //Semaphore允许多个线程访问一个临界区，所以这里必须要使用线程安全的集合类
        pool = new Vector<String>(){};
        for (int i = 0; i < size; i++) {
            pool.add(t+i);
        }
        sem = new Semaphore(size);
    }

    private String exec(Function<String, String> func){
        String t = null;
        try {
            sem.acquire();
            t = pool.remove(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            pool.add(t);
            sem.release();
        }
        return func.apply(t);
    }

    public static void main(String[] args) {
        ObjPool pool = new ObjPool(10, "2");

        pool.exec(t ->{
            System.out.println(t);
            return t;
        });
    }
}
